/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.emove.modular.system.controller;

import cn.emove.config.properties.GunsProperties;
import cn.emove.core.common.annotion.Permission;
import cn.emove.core.common.constant.factory.ConstantFactory;
import cn.emove.core.common.constant.state.TicketStatus;
import cn.emove.core.common.exception.BizExceptionEnum;
import cn.emove.core.common.page.LayuiPageFactory;
import cn.emove.core.log.LogObjectHolder;
import cn.emove.core.util.ExcelUtil;
import cn.emove.modular.system.model.TicketModel;
import cn.emove.modular.system.service.DictService;
import cn.emove.modular.system.service.TicketService;
import cn.emove.modular.system.service.UserService;
import cn.emove.modular.system.warpper.TicketWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jxl.write.WritableWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 系统管理员控制器
 *
 * @author fengshuonan
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping("/mishandleTicket")
public class MishandleTicketController extends BaseController {

    private static String PREFIX = "/modular/system/mishandleTicket/";

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;

    /**
     * 跳转到查看管理员列表的页面
     *
     * @author jiaojiaxiang
     * @Date 2019/04/18 10:50
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "mishandleTicket.html";
    }
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String orderNo,
                       @RequestParam(required = false) String contactName ,
                       @RequestParam(required = false) String createTime,
                       @RequestParam(required = false) String type,
                       @RequestParam(required = false) String describes,
                       @RequestParam(required = false) String repairType) {

        //拼接查询条件
        String beginTime = "";
        String endTime = "";
        int orderSource = 3;
        String shopName = "";
        String shopAdr ="";
        if (ToolUtil.isNotEmpty(createTime)) {
            String[] split = createTime.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }
        Page<Map<String, Object>> tickets = ticketService.selectTickets(null, orderNo,orderSource, beginTime, endTime,contactName, shopName, shopAdr,  type, null, describes, repairType);
        Page wrapped = new TicketWrapper(tickets).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);

    }

    /**
     * 导出报表
     * @return
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(@RequestParam(required = false) int orderSource,
                                    @RequestParam(required = false) String orderNo,
                                    @RequestParam(required = false) String contactName,
                                    @RequestParam(required = false) String shopName,
                                    @RequestParam(required = false) String shopAdr,
                                    @RequestParam(required = false) String createTime,
                                    @RequestParam(required = false) String type,
                                    @RequestParam(required = false) String describes,
                                    @RequestParam(required = false) String repairType,
                                    HttpServletResponse response) throws Exception {

        //拼接查询条件
        String beginTime = "";
        String endTime = "";

        if (ToolUtil.isNotEmpty(createTime)) {
            String[] split = createTime.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }
        //获取数据
        List<TicketModel> list = ticketService.selectAllTicket(orderSource,orderNo,beginTime,endTime,contactName,shopName,shopAdr,type,describes, repairType);
       /* List<TicketModel> mList = new ArrayList<>();
        for (TicketModel data : list) {
            //自定义一个新实体类，定义好要导出来的字段，把遍历出来的数据存放到一个新的list，因为会出现关联表的数据
            TicketModel sellDeal = new TicketModel();
            sellDeal.setOrderNo(data.getOrderNo()+"\t");
            sellDeal.setContactName(data.getContactName());
            sellDeal.setDescribes(data.getDescribes()+"\t");
            sellDeal.setChangeOrderReason(data.getChangeOrderReason());
            sellDeal.setOperatorName(ConstantFactory.me().getOperatorName(data.getOperatorId()));
            sellDeal.setCreateTime(String.valueOf(data.getCreateTime()));
            sellDeal.setTypeName(TicketStatus.getDescription(data.getType()));
            if(data.getUpdateTime()!=null){
                sellDeal.setUpdateTime(data.getUpdateTime());
            }
            mList.add(sellDeal);
        }*/

        // 生成Excel
        //excel标题
        String[] title={"报事单号","报事人","报事内容","转单原因","处理负责人","报事时间","状态","最新时间","报事图片","无法处理图片","处理图片"};
        //excel名称
        String fileName = "无法处理工单.xls";
        //sheet名
        String sheetName = "无法处理工单";

        WritableWorkbook wb = ExcelUtil.getMishandleWorkbook(sheetName, title, list, null);

        //响应到客户端
        try {
            wb.write();
            wb.close();
            ExcelUtil.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            HSSFWorkbook work = new HSSFWorkbook(new FileInputStream("/www/无法处理工单.xls"));
            work.write(os);
            os.close();
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        }
    }
    /**
     * 跳转至详情页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/mishandleTicket_detail")
    public String ticketDetail(@RequestParam int orderId,String typeName,Model model) {
        if (ToolUtil.isEmpty(orderId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("orderId", orderId);
        model.addAttribute("typeName", typeName);
        LogObjectHolder.me().set(orderId);
        return PREFIX + "mishandleTicket_detail.html";
    }
}
